<template>
  <el-dialog
    v-model="showDialog"
    title="商品选择器"
    width="1160px"
    :close-on-click-modal="false"
    @opened="handleDialogOpened"
  >
    <main-content-search-bar-wrapper>
      <el-tabs
        v-model="searchForm.defaultStore"
        class="demo-tabs"
      >
        <el-tab-pane
          name="0"
          label="商户商家供货"
        />
        <el-tab-pane
          name="1"
          label="联海供货"
        />
      </el-tabs>
      <!-- <search-bar inline> -->
        <!-- <template #normal> -->
        <el-form :model="searchForm" ref="searchFormRef" inline>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="商品分类">
            <!-- <el-select
              v-model="searchForm.categoryId"
              placeholder="请选择商品分类"
              clearable
            >
              <el-option
                v-for="(item) in merchantCategory"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select> -->
            <el-cascader :options="merchantCategory" :props="props1" clearable @change="productTypeChange" />
          </el-form-item>
          <el-form-item label="商家名称">
            <el-select
              v-model="storeIds"
              placeholder="请选择商家"
              clearable
            >
              <el-option
                v-for="(item) in supplierList"
                :key="item.id"
                :label="item.storeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="input-range-box">
            <el-form-item label="供货价" style="margin-right:12px" label-width="68px" 
             prop="minCost" :rules="rules.minAmount">
              <el-input style="width: 200px;" v-model="searchForm.minCost" placeholder="请输入最低金额" clearable></el-input>
            </el-form-item>
            <el-form-item  prop="maxCost" :rules="rules.maxCost">
              <template #label>
                <span>~</span>
              </template>
              <el-input style="width: 200px;" v-model="searchForm.maxCost" placeholder="请输入最高金额" clearable></el-input>
            </el-form-item>
          </el-form-item>
        </el-form>
        <!-- </template> -->
      <!-- </search-bar> -->
    </main-content-search-bar-wrapper>

    <!--    <el-row>-->
    <layout-table
      ref="goodsTableRef"
      url="mall/admin/product/pageStoreProduct"
      disable-auto-height
      :param="tableParams"
      :hide-watch="true"
      :set-search="setSearch"
    >
      <el-table-column
        label="商品图片"
        min-width="110"
      >
        <template #default="scope">
          <div
            style="width: 100px;height: 100px"
            class="flex-center"
          >
            <el-image
              style="max-width: 100px;max-height: 100px"
              :src="scope.row.thumbnailUrl"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品"
        min-width="240"
      >
        <template #default="scope">
          <div class="goods-content">
            <div class="goods-name">
              {{ scope.row.name }}
            </div>
            <div class="goods-info">
              <div class="goods-price">
                供货价：<span class="highlight">￥{{ scope.row.priceInterval }}</span>
              </div>
              <div class="goods-amount">
                库存：<span class="highlight">{{ scope.row.totalStock }}</span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品类型"
        min-width="150"
      >
        <template #default="scope">
          {{ getProductType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column
        label="商家名称"
        prop="storeName"
        min-width="150"
      />
      <el-table-column
        label="商品状态"
        min-width="100"
      >
        <template #default="scope">
          {{ scope.row.totalStock > 0 ? '出售中' : '无库存' }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否上架"
        min-width="80"
      >
        <template #default="scope">
          <span v-if="scope.row.containGoods == 1"><el-icon><Select /></el-icon></span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        min-width="120"
      >
        <template #default="scope">
          <el-button
            type="primary"
            @click="selectGoods(scope.row)"
          >
            选择
          </el-button>
        </template>
      </el-table-column>
    </layout-table>
    <template #footer>
      <el-button
        type="primary"
        @click="showDialog = false"
      >
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getStoreGoodsList } from "@/api/pointsMall";
import { IStoreGoodsPageData, IStoreGoodsPageRow } from "@/api/modules/pointsMall";

import { useGetSupplier } from "@/views/pointsMall/compositions/useGetSupplier";
import { useGetGoodsCategory } from "@/views/pointsMall/compositions/useGetGoodsCategory";
import { debounce } from "@/utils";
import { useGetGoodsType } from "@/components/goodsCenter/compositions/useGetGoodsType";
import { useGetGoodsStatus } from "@/views/pointsMall/compositions/useGetGoodsStatus";
import { ElTable } from 'element-plus'
import { useGetMerchantCategory } from "@/views/pointsMall/compositions/useGetMerchantCategory";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import { debounceUtils } from "@/utils/index.js";

const props = defineProps<{
  show: boolean,
}>()

const emits = defineEmits(['update:show', 'confirm', 'cancel'])
const store = useStore()
const router = useRouter()
const { mallConfig } = useMallConfig();
const goodsTableRef = ref<InstanceType<typeof ElTable>>()
const searchForm = reactive<Partial<IStoreGoodsPageData>>({
  mallId: mallConfig.value.id,
  name: '',
  storeIds: [],
  categoryId: null,
  defaultStore:0,
  minCost:null,
  maxCost:null
})
const tableParams=ref<Partial<IStoreGoodsPageData>>({
  mallId: mallConfig.value.id,
  name: '',
  storeIds: [],
  categoryId: null,
  defaultStore:0,
  minCost:null,
  maxCost:null
})
const searchFormRef=ref()
const setSearch=ref(0)
const searchList=debounceUtils(()=>{
  setSearch.value++
},800)
watch(searchForm,()=>{
  searchFormRef.value?.validate((valid:boolean)=>{
    if(valid){
      tableParams.value=Object.assign({},searchForm)
      tableParams.value.minCost=searchForm.minCost?(searchForm.minCost*100):null
      tableParams.value.maxCost=searchForm.maxCost?(searchForm.maxCost*100):null
      searchList()
    }
  })
})
const props1 = {
  checkStrictly: true,
  value:'id',
  label:'categoryName'
}
const storeIds = ref<string>()
watch(storeIds, (newVal) => {
  searchForm.storeIds = newVal === '' || newVal === undefined ? [] : [newVal]
})
const { supplierList, getSupplier } = useGetSupplier()
const { merchantCategory, getMerchantCategory } = useGetMerchantCategory()

const goodsList = ref<IStoreGoodsPageRow[]>([])
// const _getStoreGoodsList = async () => {
// const rs = await getStoreGoodsList({...searchForm, ...pageInfo})
// goodsList.value = rs.payload ?? []
// pageInfo.totalResult = rs?.page?.totalResult ?? 0
// }
// const debounceSearch = debounce(_getStoreGoodsList, 700, false)
// watch(searchForm, () => {
//   pageInfo.currentPage = 1
//   debounceSearch()
// })

const { getProductType } = useGetGoodsType()

const showDialog = computed({
  get() {
    return props.show
  },
  set(val) {
    return emits("update:show", val)
  }
})
const productTypeChange=(value:any)=>{
  if(value.length){
    searchForm.categoryId=value[value.length-1]
  }else{
    searchForm.categoryId=null
  }
  
}
const selectGoods = (rowData: IStoreGoodsPageRow) => {
  showDialog.value = false;
  router.push({
    path: '/mall/product/list/configureGoods',
    query: {
      id: rowData.id
    }
  })
}

const handleDialogOpened = () => {
  getMerchantCategory({
    defaultStore:searchForm.defaultStore!
  })
  getSupplier({
    defaultStore:searchForm.defaultStore!
  })
  nextTick(()=>{
    searchFormRef.value?.resetFields()
  })
}
watch(() => searchForm.defaultStore, (val) => {
  if (val) {
    searchForm.name='';
    searchForm.storeIds=[];
    searchForm.categoryId=null;
    storeIds.value=''
    getMerchantCategory({
      defaultStore:val
    })
    getSupplier({
      defaultStore:val
    })
  }
}, {deep:true});

const rules={
  minAmount:[{
      trigger:'blur',
      validator:(rule,value,callback)=>{
        if(value){
          if(!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
            callback('请输入正确格式,保留两位小数!')
          }else if(+value>9999999999){
            callback('超过上限【99,9999,9999】')
          }else if(searchForm.maxCost&&+value>searchForm.maxCost){
            callback('请输入正确的范围!')
          }else{
            callback()
          }
        }else{
          callback()
        }
      }
    }
  ],
  maxAmount:[{
      trigger:'blur',
      validator:(rule,value,callback)=>{
        if(value){
          if(!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
            callback('请输入正确格式,保留两位小数!')
          }else if(+value>9999999999){
            callback('超过上限【99,9999,9999】')
          }else if(searchForm.minCost&&+value<searchForm.minCost){
            callback('请输入正确的范围!')
          }else{
            callback()
          }
        }else{
          callback()
        }
      }
    }]
}
</script>

<style scoped lang="scss">
.goods-content {
  padding: 5px 0;

  .goods-name {
    margin-bottom: 10px;
  }

  .goods-info {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    width: 100%;

    .goods-amount {
      max-width: 50%;
      min-width: 90px;
      margin-left: 4px;
    }

  }

  .highlight {
    color: var(--el-color-warning-dark-2)
  }
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;

  .left {
    display: flex;
    align-items: center;

    .block {
      padding: 0 10px;
    }
  }
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
:deep(.el-cascader) {
  .el-input .el-input__suffix-inner .el-icon {
    &::before {
      display: none;
    }
  }
}
</style>
